import { uploadActionUrl } from '../utils/tools'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons'
import { message, Upload } from 'antd'
import { useState } from 'react'

const getBase64 = (img, callback) => {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传jpg或者png图片!')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!')
  }
  return isJpgOrPng && isLt2M
}
const ImageUpload = (props) => {
  const [loading, setLoading] = useState(false)
  const { imageUrl, setImageUrl } = props
  const handleChange = (info) => {
    console.log(info)
    if (info.file.status === 'uploading') {
      setLoading(true)
      return
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      // getBase64(info.file.originFileObj, (url) => {
      //   setLoading(false);
      //   setImageUrl(url);
      // });
      setLoading(false)
      setImageUrl(info.file.response.data.url)
    }
  }
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8
        }}
      >
        上传图片
      </div>
    </div>
  )
  return (
    <Upload
      //服务器接口的参数名称
      name="file"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      // 上传接口的API
      action={uploadActionUrl}
      // headers={{
      //   Authorization: xxx
      // }}
      beforeUpload={beforeUpload}
      onChange={handleChange}
    >
      {imageUrl ? (
        <img
          src={imageUrl}
          alt="avatar"
          style={{
            width: '100%'
          }}
        />
      ) : (
        uploadButton
      )}
    </Upload>
  )
}
export default ImageUpload
